package com.zheng.common.util;

import org.apache.commons.io.output.FileWriterWithEncoding;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.*;
import java.net.URL;
import java.util.Properties;

/**
 * Velocity工具类
 * Created by ZhangShuzheng on 2017/1/10.
 */
public class VelocityUtil {

    /**
     * 根据模板生成文件
     *
     * @param inputVmFilePath 模板路径
     * @param outputFilePath  输出文件路径
     * @param context
     * @throws Exception
     */
    public static void generate(String inputVmFilePath, String outputFilePath, VelocityContext context) throws Exception {
        File fileOut = new File(outputFilePath);
        if (fileOut.exists()) {
            fileOut.delete();
        }

        URL url = VelocityUtil.class.getResource("");
        String protocol = url.getProtocol();

        if ("jar".equals(protocol)) {
            generateJar(inputVmFilePath, outputFilePath, context);
        } else if ("file".equals(protocol)) {
            // 非jar 中 （文件class 中）
            generateFile(inputVmFilePath, outputFilePath, context);
        }
    }


    // yihr
    public static void generateFile(String inputVmFilePath, String outputFilePath, VelocityContext context) throws Exception {
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            inputVmFilePath = VelocityUtil.class.getClassLoader().getResource(inputVmFilePath).getPath().replaceFirst("/", "");
        } else {
            inputVmFilePath = VelocityUtil.class.getClassLoader().getResource(inputVmFilePath).getPath();
        }

        try {
            Properties properties = new Properties();
            properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, getPath(inputVmFilePath));
            Velocity.init(properties);
            //VelocityEngine engine = new VelocityEngine();
            Template template = Velocity.getTemplate(getFile(inputVmFilePath), "utf-8");
            File outputFile = new File(outputFilePath);
            FileWriterWithEncoding writer = new FileWriterWithEncoding(outputFile, "utf-8");
            template.merge(context, writer);
            writer.flush();
            writer.close();
        } catch (Exception ex) {
            throw ex;
        }
    }

    // yihr
    public static void generateJar(String inputVmFilePath, String outputFilePath, VelocityContext context) throws Exception {
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init();

        final String templatePath = inputVmFilePath;
        InputStream input = VelocityUtil.class.getClassLoader().getResourceAsStream(templatePath);
        if (input == null) {
            throw new IOException("Template file doesn't exist");
        }
        Template template = ve.getTemplate(templatePath, "UTF-8");

        File outputFile = new File(outputFilePath);
        FileWriterWithEncoding writer = new FileWriterWithEncoding(outputFile, "utf-8");

//        InputStreamReader reader = new InputStreamReader(input);
//        BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
        // 与 template.merge(context, writer); 作用一样，同时存在会重复
//        if (!ve.evaluate(context, writer, templatePath, reader)) {
//            throw new Exception("Failed to convert the template into html.");
//        }

        template.merge(context, writer);
        writer.flush();
        writer.close();
    }


    /**
     * 根据文件绝对路径获取目录
     *
     * @param filePath
     * @return
     */
    public static String getPath(String filePath) {
        String path = "";
        if (StringUtils.isNotBlank(filePath)) {
            path = filePath.substring(0, filePath.lastIndexOf("/") + 1);
        }
        return path;
    }

    /**
     * 根据文件绝对路径获取文件
     *
     * @param filePath
     * @return
     */
    public static String getFile(String filePath) {
        String file = "";
        if (StringUtils.isNotBlank(filePath)) {
            file = filePath.substring(filePath.lastIndexOf("/") + 1);
        }
        return file;
    }

}
